package com.zhanggm.springcloud.jpa.service.impl;

import com.zhanggm.springcloud.jpa.repository.TbAreaRepository;
import com.zhanggm.springcloud.jpa.service.TbAreaService;
import com.zhanggm.springcloud.jpa.entity.TbArea;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.geom.Area;
import java.util.List;
import java.util.stream.Collectors;

/**
@author Zhanggm
*/
@Service
public class TbAreaServiceImpl implements TbAreaService {

	@Resource
	private TbAreaRepository areaRepository;

	@Override
	public TbArea getById(Integer id) {
		return areaRepository.findById(id).get();
	}

	@Override
	public List<TbArea> getTreeByPid(Integer pid) {
        List<TbArea> all = areaRepository.findAll();

//        List<TbArea> areaList = areaRepository.findByPid(pid);
        List<TbArea> areaList = findByPid(all,pid);
        getSubAreaList(all,areaList);
        return areaList;
	}

	private List<TbArea> findByPid(List<TbArea> list, Integer pid){
        List<TbArea> subArea = list.stream().filter(area -> area.getPid() == pid).collect(Collectors.toList());
        return subArea;
    }

    /**
     * 递归查询孩子
     * @param areaList
     */
	private void getSubAreaList(List<TbArea> all,List<TbArea> areaList){
        areaList.forEach(area->{
            List<TbArea> subAreaList = findByPid(all,area.getId());/*areaRepository.findByPid(area.getId());*/
            if(subAreaList!=null && subAreaList.size()>0){
                area.setSubArea(subAreaList);
                getSubAreaList(all,subAreaList);
            }
        });
    }


	@Override
	public List<TbArea> getTreeAll() {
		return getTreeByPid(1);
	}

    @Override
    public List<TbArea> getListByPid(Integer pid) {
        return areaRepository.findByPid(pid);
    }
}
